//
//  PersonalSettingsViewController.m
//  Estate
//
//  Created by wangdongdong on 2016/11/25.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define kLocalNotificationKey @"kLocalNotificationKey"
#import "NSString+Extension.h"
#define SEC1HEIGHT 10
#define SEC2HEIGHT 30
#import "PersonalSettingsViewController.h"
#import "TTInitCell.h"
#import "B_SwitchCell.h"
#import "AppDelegate.h"
#import "LBXAlertAction.h"
#import "LoginViewController.h"
@interface PersonalSettingsViewController ()<UIAlertViewDelegate>
{
    NSMutableDictionary *settingDic;
    NSArray *titleArray;
}
@property (strong, nonatomic)TPKeyboardAvoidingTableView *tableView;
//是否开启定时刷新
@property (assign,nonatomic)BOOL isTiming;
//定时时长
@property (assign,nonatomic)NSInteger time;

//是否开启推送
@property (assign,nonatomic)BOOL isTuisong;

@end

@implementation PersonalSettingsViewController

- (UITableView *)tableView{
    if(!_tableView){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:self.view.bounds];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=[UIColor colorWithRed:0.96 green:0.97 blue:0.97 alpha:1.00];
        [_tableView registerNib:[UINib nibWithNibName:@"B_SwitchCell" bundle:nil] forCellReuseIdentifier:@"switchCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TTInitCell" bundle:nil] forCellReuseIdentifier:@"TTInitCell"];
        [LSUtility setExtraCellLineHidde:_tableView tabHeader:NO tabFooter:NO];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createView];

}

- (void)createView{
    titleArray = @[@"开启同步提示",@"退出并初始化本地数据"];
    self.title=@"个人设置";
    settingDic=DEF_PERSISTENT_GET_OBJECT(USERID);
    //得到本地存储的刷新频率设置
    if(settingDic){
        if([settingDic[@"isTiming"] isEqualToString:@"yes"]){
            self.isTiming=YES;
        }else{
            self.isTiming=NO;
        }
        self.time=[settingDic[@"time"]integerValue];
        self.time=self.time==0?60:self.time;
    }else{
        self.isTiming=NO;
        self.time=60;
    }
    NSString *isTuisong =DEF_PERSISTENT_GET_OBJECT(@"isTuisong");
    
    if ([isTuisong isEqualToString:@"true"]) {
        self.isTuisong = YES;
    }else{
        self.isTuisong = NO;
    }
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];

    
}

#pragma mark - 保存
- (void)clickSave{
    //开启定时刷新
    NSDictionary *dic;
    if(self.isTiming){
        if(self.time==0){
            [LSUtility showToastWithMessage:@"刷新频率必须大与0！" inView:self.view Andtime:1.2];
            return;
        }
        if(!self.time){
            self.time=60;
        }
        //存入状态
        dic=@{@"isTiming":@"yes",@"time":@(self.time)};
        NSMutableDictionary *dicc=[NSMutableDictionary dictionaryWithDictionary:dic];
        //存入刷新时间
        DEF_PERSISTENT_SET_OBJECT(dicc, USERID);
        NSLog(@"当前保存时间:%@",[LSUtility nowTime]);
        //立即验证一次
        TimeingSynchronization *timeing=[[TimeingSynchronization alloc]init];
        [timeing isSyncLocalData];
        
    }else{
        dic=@{@"isTiming":@"no",@"time":@(self.time)};
        NSMutableDictionary *dicc=[NSMutableDictionary dictionaryWithDictionary:dic];
        //存入刷新时间
        DEF_PERSISTENT_SET_OBJECT(dicc, USERID);
    }
    
    
    NSString *isTuisong =DEF_PERSISTENT_GET_OBJECT(@"isTuisong");

    if ([isTuisong isEqualToString:@"true"]&&self.isTuisong) {
        
    }else if (self.isTuisong) {
        DEF_PERSISTENT_SET_OBJECT(@"true", @"isTuisong");
//        [LSUtility tuisong];
    }else{
        DEF_PERSISTENT_SET_OBJECT(@"false", @"isTuisong");
    }
    //发送appdelegate通知 全局设置刷新 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadBtn" object:nil userInfo:dic];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma  mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.isTiming&&section==0){
        return 2;
    }else{
        return 1;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return titleArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        return 44;
    }else{
        return 74;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0 ){
        if (indexPath.row==0) {
            B_SwitchCell *cell=[tableView dequeueReusableCellWithIdentifier:@"switchCell" forIndexPath:indexPath];
            cell.persinal=@"setting";
            cell.title.text=titleArray[indexPath.section];
            cell.kaiguan.on=self.isTiming;
            cell.sValueChangeBlock=^(UISwitch *sender){
                self.isTiming=sender.on;
                [self.tableView reloadData];
            };
            return cell;
        }else{
            SyncFrequencyCell *cell=[SyncFrequencyCell cellWithTableView:tableView];
            // 默认60
            cell.timeText.text=[NSString stringWithFormat:@"%li",self.time];
            cell.timeChangeBlock=^(NSString *timestr){
                self.time=[timestr integerValue];
            };
            return cell;
        }
   
    }else if(indexPath.section == 1){
        if (indexPath.row==0) {
            TTInitCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TTInitCell" forIndexPath:indexPath];
            [cell.confirm addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }else if(indexPath.section == 2){
        if (indexPath.row==0) {
            B_SwitchCell *cell=[tableView dequeueReusableCellWithIdentifier:@"switchCell" forIndexPath:indexPath];
            cell.persinal=@"setting";
            cell.title.text=titleArray[indexPath.section];
            cell.kaiguan.on=self.isTuisong;
            cell.sValueChangeBlock=^(UISwitch *sender){
                self.isTuisong=sender.on;
            };
            return cell;
        }
    }
    static NSString *rid=@"asdasd";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:rid];
    
    if(cell==nil){
        
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:rid];
        
    }
    
    return cell;
}
-(void)confirm{
    NSLog(@"退出");
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"确认退出登录并删除本地数据" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];

    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%d",buttonIndex);
    if (buttonIndex == 1) {
   
        NSString *userName=DEF_PERSISTENT_GET_OBJECT(@"loginUserss");
        NSString *deviceId=DEF_PERSISTENT_GET_OBJECT(@"deviceId");
        
        if(userName&&deviceId){
            [LSHttpTool PostExit:URL_LOGIN parameters:@{@"username":userName,@"phoneId":deviceId,@"loginState":@"false"} success:^(id responseObject) {
                NSLog(@"退出登录：%@",responseObject);
                [self logout:NO];
                
            } failure:^(NSError *error) {
                [LSUtility showToastWithMessage:@"服务器异常，同步失败。" inView:kKeyWindow Andtime:1.5];
                [self logout:YES];
                
            }];
        
        }
        
    }
    
}
-(void)logout:(BOOL)isShow{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    LoginViewController *loginCtr=[[LoginViewController alloc]init];
    loginCtr.isShow = isShow;
    DEF_PERSISTENT_REMOVE(@"role");
    DEF_PERSISTENT_REMOVE(@"loginuserPost");
    DEF_PERSISTENT_REMOVE(@"userid");
    DEF_PERSISTENT_REMOVE(@"proid");
    //记录当前服务器ip
    DEF_PERSISTENT_SET_OBJECT(DEFIP, @"oldServiceIP");
    NSString *path = [NSString getPathWith:@"/standardClass.plist"];
    NSString *path1 = [NSString getPathWith:@"/standardKey.plist"];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:path];
    if (blHave) {
        [[NSFileManager defaultManager]  removeItemAtPath:path error:nil];
    }
    BOOL blHave1=[[NSFileManager defaultManager] fileExistsAtPath:path1];
    if (blHave1) {
        [[NSFileManager defaultManager]  removeItemAtPath:path1 error:nil];
    }
    loginCtr.flag=@"shanchu";
    [[UIApplication sharedApplication].delegate window].rootViewController=loginCtr;
    // 清除记录的领导
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLeader"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
